# 语音识别模块：负责监听语音、解析指令（加减分）
import speech_recognition as sr
from config.settings import (
    MICROPHONE_INDEX, NOISE_CALIBRATION_DURATION,
    VOICE_LISTEN_TIMEOUT, VOICE_PHRASE_LIMIT
)

# 初始化语音识别引擎
recognizer = sr.Recognizer()
# 初始化麦克风（默认0，蓝牙麦克风需先查看设备索引）
try:
    microphone = sr.Microphone(device_index=MICROPHONE_INDEX)
except sr.RequestError as e:
    print(f"❌ 麦克风初始化失败：{e}")
    microphone = None

def calibrate_noise():
    """校准环境噪音（提升识别准确率）"""
    if not microphone:
        return False
    with microphone as source:
        recognizer.adjust_for_ambient_noise(source, duration=NOISE_CALIBRATION_DURATION)
    print("✅ 环境噪音校准完成")
    return True

def listen_voice():
    """监听语音，返回识别到的文本"""
    if not microphone:
        return None
    try:
        with microphone as source:
            audio = recognizer.listen(
                source, timeout=VOICE_LISTEN_TIMEOUT, phrase_time_limit=VOICE_PHRASE_LIMIT
            )
        # 识别中文语音
        text = recognizer.recognize_google(audio, language='zh-CN')
        return text.strip()
    except sr.WaitTimeoutError:
        # 没有检测到语音，正常跳过
        return None
    except sr.UnknownValueError:
        # 识别不出有效语音（噪音等）
        print("❌ 未识别到有效语音")
        return None
    except Exception as e:
        # 其他错误（麦克风异常等）
        print(f"❌ 语音识别出错：{e}")
        return None

def parse_score_command(text, student_names):
    """
    解析语音指令，提取“姓名”“操作类型”“分数”
    :param text: 识别到的语音文本
    :param student_names: 学生姓名列表（来自人脸库）
    :return: 指令信息（字典）或None（无效指令）
    """
    if not text:
        return None
    text = text.strip().lower()
    print(f"🎤 识别到语音：{text}")
    
    command = {"name": None, "action": None, "score": 1}  # 默认1分
    
    # 1. 提取操作类型（加分/减分）
    add_keywords = ["加", "增加", "加分"]
    subtract_keywords = ["减", "减少", "减分"]
    for kw in add_keywords:
        if kw in text:
            command["action"] = "add"
            break
    if not command["action"]:
        for kw in subtract_keywords:
            if kw in text:
                command["action"] = "subtract"
                break
    if not command["action"]:
        return None  # 无加减分关键词，不是积分指令
    
    # 2. 提取分数（支持数字和中文数字）
    score_map = {
        "一": 1, "二": 2, "三": 3, "四": 4, "五": 5,
        "六": 6, "七": 7, "八": 8, "九": 9, "十": 10,
        "1": 1, "2": 2, "3": 3, "4": 4, "5": 5,
        "6": 6, "7": 7, "8": 8, "9": 9, "10": 10
    }
    for kw, num in score_map.items():
        if kw in text:
            command["score"] = num
            break
    
    # 3. 提取学生姓名（必须在学生列表中）
    for name in student_names:
        if name in text:
            command["name"] = name
            break
    
    return command if command["name"] else None

# 测试麦克风设备索引（如果不知道蓝牙麦克风索引，运行这个函数）
def list_microphones():
    """列出所有可用麦克风设备，方便查看索引"""
    print("📢 可用麦克风设备：")
    for i, name in enumerate(sr.Microphone.list_microphone_names()):
        print(f"  索引{i}：{name}")

# 如果你不知道蓝牙麦克风